from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models.car import Car
from app.models.brand import Brand

car_bp = Blueprint('car', __name__)

@car_bp.route('/brands', methods=['GET'])
@jwt_required()
def get_brands():
    brands = Brand.query.all()
    return jsonify([brand.to_dict() for brand in brands]), 200

@car_bp.route('/brands/<int:brand_id>', methods=['GET'])
@jwt_required()
def get_brand(brand_id):
    brand = Brand.query.get(brand_id)
    if not brand:
        return jsonify({'message': '品牌不存在'}), 404
    return jsonify(brand.to_dict()), 200

@car_bp.route('/brands', methods=['POST'])
@jwt_required()
def create_brand():
    data = request.get_json()
    
    if not data.get('name'):
        return jsonify({'message': '品牌名称为必填项'}), 400
    
    # 检查品牌名称是否已存在
    if Brand.query.filter_by(name=data['name']).first():
        return jsonify({'message': '品牌名称已存在'}), 400
    
    try:
        brand = Brand(
            name=data['name'],
            logo=data.get('logo'),
            description=data.get('description'),
            country=data.get('country'),
            founded_year=data.get('founded_year')
        )
        db.session.add(brand)
        db.session.commit()
        
        return jsonify({
            'message': '品牌创建成功',
            'brand': brand.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建失败: {str(e)}'}), 500

@car_bp.route('/cars', methods=['GET'])
@jwt_required()
def get_cars():
    # 获取查询参数
    brand_id = request.args.get('brand_id', type=int)
    min_price = request.args.get('min_price', type=float)
    max_price = request.args.get('max_price', type=float)
    
    # 构建查询
    query = Car.query
    
    if brand_id:
        query = query.filter(Car.brand_id == brand_id)
    
    if min_price:
        query = query.filter(Car.price >= min_price)
    
    if max_price:
        query = query.filter(Car.price <= max_price)
    
    # 执行查询
    cars = query.all()
    
    return jsonify([car.to_dict() for car in cars]), 200

@car_bp.route('/cars/<int:car_id>', methods=['GET'])
@jwt_required()
def get_car(car_id):
    car = Car.query.get(car_id)
    if not car:
        return jsonify({'message': '车辆不存在'}), 404
    return jsonify(car.to_dict()), 200

@car_bp.route('/cars', methods=['POST'])
@jwt_required()
def create_car():
    data = request.get_json()
    
    # 验证必填字段
    if not data.get('name') or not data.get('brand_id') or not data.get('price'):
        return jsonify({'message': '车名、品牌ID和价格为必填项'}), 400
    
    # 检查品牌是否存在
    brand = Brand.query.get(data['brand_id'])
    if not brand:
        return jsonify({'message': '品牌不存在'}), 400
    
    try:
        car = Car(
            name=data['name'],
            brand_id=data['brand_id'],
            price=data['price'],
            model=data.get('model'),
            year=data.get('year'),
            color=data.get('color'),
            engine=data.get('engine'),
            transmission=data.get('transmission'),
            fuel_type=data.get('fuel_type'),
            mileage=data.get('mileage'),
            seats=data.get('seats'),
            description=data.get('description'),
            image=data.get('image'),
            stock=data.get('stock', 0)
        )
        db.session.add(car)
        db.session.commit()
        
        return jsonify({
            'message': '车辆创建成功',
            'car': car.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建失败: {str(e)}'}), 500

@car_bp.route('/cars/<int:car_id>', methods=['PUT'])
@jwt_required()
def update_car(car_id):
    car = Car.query.get(car_id)
    if not car:
        return jsonify({'message': '车辆不存在'}), 404
    
    data = request.get_json()
    
    # 检查品牌是否存在
    if data.get('brand_id'):
        brand = Brand.query.get(data['brand_id'])
        if not brand:
            return jsonify({'message': '品牌不存在'}), 400
    
    try:
        # 更新车辆信息
        for key, value in data.items():
            if hasattr(car, key) and key != 'id':
                setattr(car, key, value)
        
        db.session.commit()
        return jsonify({
            'message': '车辆信息更新成功',
            'car': car.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新失败: {str(e)}'}), 500

@car_bp.route('/cars/<int:car_id>', methods=['DELETE'])
@jwt_required()
def delete_car(car_id):
    car = Car.query.get(car_id)
    if not car:
        return jsonify({'message': '车辆不存在'}), 404
    
    try:
        db.session.delete(car)
        db.session.commit()
        return jsonify({'message': '车辆删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除失败: {str(e)}'}), 500